# demo1/utils/rl_sms.py
import random
import logging
from django.core.cache import cache

logger = logging.getLogger(__name__)


def send_verification_code(phone):
    """
    发送验证码到指定手机号
    """
    # 生成6位随机验证码
    code = str(random.randint(100000, 999999))

    # 存储到缓存中，设置5分钟过期时间
    cache_key = f"sms_code_{phone}"
    cache.set(cache_key, code, timeout=60*5)  # 5分钟有效期

    # 开发环境下打印到终端
    logger.info(f"验证码已发送到 {phone}: {code}")
    print(f"验证码已发送到 {phone}: {code}，验证码为:{code}")

    return code


def verify_code(phone, input_code):
    """
    验证手机号和验证码是否匹配
    """
    cache_key = f"sms_code_{phone}"
    stored_code = cache.get(cache_key)

    if not stored_code:
        return False

    # 验证码匹配且未过期
    if stored_code == input_code:
        # 验证成功后删除验证码
        cache.delete(cache_key)
        return True

    return False